#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#define BUFSIZE 1024
#define PORT    9966
const char* clientip = "0";
void        sign_handle(int sign)
{
    /*do nothing*/
    printf("signal id = %d \n", sign);
}
int main()
{
    int sockfd, ret;
    signal(SIGPIPE, sign_handle);

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sockfd) {
        perror("socket");
        return -1;
    }
    printf("socket create success\n");
    //客户端可以不用绑定

    // inter协议族
    struct sockaddr_in connectaddr;
    connectaddr.sin_family = AF_INET;
    //客户端和服务端的端口号必须相等
    connectaddr.sin_port = htons(PORT);
    // ip地址为服务器的ip地址
    // connectaddr.sin_addr.s_addr = inet_addr("0");
    connectaddr.sin_addr.s_addr = inet_addr(clientip);

    ret = connect(sockfd, (struct sockaddr*)&connectaddr, sizeof(connectaddr));
    /**
     * @description:向服务器发起连接
     * @param
     * {*}第一个参数：套接字，第二个参数：指向sockaddr的指针，第三个参数：sockaddr结构体大小
     * @return {*}成功返回0，失败返回-1；
     */
    if(-1 == ret) {
        perror("connect:");
        return -1;
    }
    printf("connect success\n");
    char buf[BUFSIZE] = "12345";
    while(1) {
        sleep(1);
        int ret = send(sockfd, buf, strlen(buf), 0);
        if(0 == ret) {
            printf("client is closed\n");
            return 0;
        }
        if(0 > ret) {
            if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
                printf("no error\n");
                continue;
            } else {
                perror("send");
                return -1;
            }
        }
        ret == recv(sockfd, buf, BUFSIZE, 0);
        if(0 >= ret) {
            perror("recv");
            break;
        }
        printf("%s\n", buf);
    }
    printf("end\n");
    close(sockfd);
    return 0;
}
